package io.gitee.caoxiaoyu97.log4j.defender.message.trace;

import io.gitee.caoxiaoyu97.log4j.defender.matcher.KeyMatcher;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

public abstract class MessageDefender {
    protected List<KeyMatcher> matchers;
    protected String markerValue;
    protected Integer maxLen;
    protected Pattern invalidValuePattern = Pattern.compile(".*(\"|\\[|\\]|\\{|\\}|\\\\)+.*");

    public MessageDefender(List<KeyMatcher> matchers, String maxLen, String markerValue) {
        this.matchers = matchers;
        this.maxLen = getMaxStep(maxLen);
        this.markerValue = getMarkerValue(markerValue);
    }

    public abstract String doDesensitize(String paramString);

    protected String getMarkerValue(String markValue) {
        try {
            return (StringUtils.isEmpty(markValue) || StringUtils.isEmpty(markValue.trim()) || this.invalidValuePattern
                    .matcher(markValue).matches()) ? "******" : markValue;
        } catch (Exception e) {
            return "******";
        }
    }

    protected Integer getMaxStep(String maxLen) {
        try {
            Integer max = Integer.valueOf(Integer.parseInt(maxLen));
            return Integer.valueOf((max.intValue() <= 0) ? Integer.parseInt("1000") : max.intValue());
        } catch (Exception e) {
            return Integer.valueOf(Integer.parseInt("1000"));
        }
    }
}
